package com.foryou.swkj.core.jdbc;

import org.springframework.jdbc.core.*;
import org.springframework.jdbc.object.StoredProcedure;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class SpringStoredProcedure extends StoredProcedure {
    public ArrayList set = new ArrayList();
	private Map<String, ?> inParam;
	private RowMapper rm = new RowMapper() {
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			return null;
		}
	};

	private RowMapperResultSetExtractor callback = new RowMapperResultSetExtractor(
			this.rm) {
		public void processRow(ResultSet rs) throws SQLException {
			int count = rs.getMetaData().getColumnCount();
			String[] header = new String[count];
			for (int i = 0; i < count; ++i)
				header[i] = rs.getMetaData().getColumnName(i + 1);
			while (rs.next()) {
				HashMap row = new HashMap(count + 7);
				for (int i = 0; i < count; ++i)
					row.put(header[i], rs.getString(i + 1));
				SpringStoredProcedure.this.set.add(row);
			}
		}
	};

	public SpringStoredProcedure(DataSource ds, String SQL, boolean isFunction) {
		setDataSource(ds);
		setSql(SQL);
		setFunction(isFunction);
	}

	public SpringStoredProcedure(JdbcTemplate jdbcTemplate, String SQL) {
		setJdbcTemplate(jdbcTemplate);
		setSql(SQL);
	}

	public SpringStoredProcedure(JdbcTemplate jdbcTemplate, String SQL,
                                 boolean isFunction) {
		setJdbcTemplate(jdbcTemplate);
		setSql(SQL);
		setFunction(isFunction);
	}

	public void setOutParameter(String column, int type) {
		declareParameter(new SqlOutParameter(column, type, this.callback));
	}

	public void setParameter(String column, int type) {
		declareParameter(new SqlParameter(column, type));
	}

	public void SetInParam(Map<String, ?> inParam) {
		this.inParam = inParam;
	}

	public Map<String, Object> execute() {
		compile();
		return execute(this.inParam);
	}
}